package cn.org.tpeach.nosql.redis.controller;

import cn.org.tpeach.nosql.constant.PublicConstant;
import cn.org.tpeach.nosql.exception.ServiceException;
import cn.org.tpeach.nosql.framework.LarkFrame;
import cn.org.tpeach.nosql.framework.ServiceProxy;
import io.lettuce.core.RedisException;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;
@Slf4j
public abstract class BaseController{

    public static <T> ResultRes<T> dispatcher(Supplier<T> function ) {
        try {
            //成功返回
            T t = function.get();
            return new ResultRes<T>(true, t, null);
        } catch (Exception e) {
            if (e instanceof ServiceException) {
                if (!PublicConstant.ProjectEnvironment.RELEASE.equals(LarkFrame.getProjectEnv())) {
                    log.error("业务接口异常", e);
                }
                return new ResultRes<T>(false, null, e.getMessage());
            } else if (e instanceof RedisException) {
                if (!PublicConstant.ProjectEnvironment.RELEASE.equals(LarkFrame.getProjectEnv())) {
                    log.error("业务接口异常", e);
                }
                String msg = e.getMessage();
                Throwable ex = e;
                while (ex.getCause() != null) {
                    ex = ex.getCause();
                    msg =ex.getClass().getName()+":"+ ex.getMessage();
                }
                return new ResultRes<T>(false, null, msg);
            } else {
                log.error("服务接口异常", e);
                return new ResultRes<T>(false, null, ServiceProxy.getStackTrace(e));
            }
        }
    }
}